using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using RBAC.Api.Demain.ContentManagement;
using RBAC.Api.Erroc;
using RBAC.Api.Infaction;
using RBAC.Api.Writh.Command.ContentManagement;

namespace RBAC.Api.Writh.CommandHandler.ContentManagement
{
    public class UpdateDepartmentCommandHandler : IRequestHandler<UpdateDepartmentCommand, APIResult<object>>
    {
        private readonly IBaseRepositry<DepartmentModel> baseRepositry;
        private readonly IMapper mapper;
        private readonly ILogger<UpdateDepartmentCommandHandler> logger;

        public UpdateDepartmentCommandHandler(
            IBaseRepositry<DepartmentModel> baseRepositry,
            IMapper mapper,
            ILogger<UpdateDepartmentCommandHandler> logger)
        {
            this.baseRepositry = baseRepositry;
            this.mapper = mapper;
            this.logger = logger;
        }

        public async Task<APIResult<object>> Handle(UpdateDepartmentCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = ResultCode.Success;
            result.Message = "修改科室成功";

            var strategy = baseRepositry.Context.Database.CreateExecutionStrategy();
            await strategy.ExecuteAsync(async () =>
            {
                using (var tran = await baseRepositry.Context.Database.BeginTransactionAsync())
                {
                    try
                    {
                        // 查找要修改的科室
                        var existingDepartment = baseRepositry.GetAll().FirstOrDefault(d => d.Id == request.Id);
                        if (existingDepartment == null)
                        {
                            result.Code = ResultCode.Fail;
                            result.Message = $"未找到ID为{request.Id}的科室";
                            return;
                        }

                        // 直接更新现有实体的属性，而不是创建新实体
                        mapper.Map(request, existingDepartment);
                        existingDepartment.ModifyTime = DateTime.Now;

                        await baseRepositry.Update(existingDepartment);

                        await tran.CommitAsync();
                        logger.LogInformation($"成功修改科室，ID: {request.Id}");
                    }
                    catch (Exception ex)
                    {
                        await tran.RollbackAsync();
                        logger.LogError(ex, $"修改科室失败，ID: {request.Id}，错误: {ex.Message}");
                        result.Code = ResultCode.Fail;
                        result.Message = $"修改科室失败: {ex.Message}";
                    }
                }
            });

            return await Task.FromResult(result);
        }
    }
}